package concurrency;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Auther: 肖冬
 * @Date: 2020/8/14 23:44
 * @Description: 多线程同步工具：栅栏
 * 它的作用就是会让所有线程都等待完成后才会继续下一步行动。
 */
public class CyclicBarrierTest {
    public static void main(String[] args) {
        int count = 100;
        CyclicBarrier cyclicBarrier = new CyclicBarrier(count);
        ExecutorService executorService = Executors.newFixedThreadPool(count);
        for (int i = 0; i < count; i++) {
            executorService.execute(new CyclicBarrierTest().new Task(cyclicBarrier));
        }

        executorService.shutdown();
        while (!executorService.isTerminated()){
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    class Task implements Runnable{
        private CyclicBarrier cyclicBarrier;

        public Task(CyclicBarrier cyclicBarrier) {
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try{
                cyclicBarrier.await();
                System.out.println("做点什么"+System.currentTimeMillis());
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
